package com.dy.栈.链栈;

import com.dy.栈.IStack;
import com.dy.线性表.链表.Node;

public class LinkStack implements IStack {

    private Node top;

    @Override
    public void clear() {
        top = null;
    }

    @Override
    public boolean isEmpty() {
        return top == null;
    }

    @Override
    public int length() {
        Node p = top;
        int len = 0;
        while (p != null) {
            len++;
            p = p.next;
        }
        return len;
    }

    @Override
    public Object peek() {
        if (isEmpty())
            return null;
        else
            return top.data;
    }

    @Override
    public void push(Object x) throws Exception {
        Node p = new Node(x);
        p.next = top;
        top = p;

    }

    @Override
    public Object pop() {
        if (isEmpty()) {
            return null;
        }
        else{
            Object d = top.data;
            top = top.next;
            return d;
        }
    }

    public void display() {
        Node p = top;
        while (p != null) {
            System.out.println(p.data.toString() + " ");
            p = p.next;
        }
    }
}
